import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, message } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import AddFrom from './components/AddForm';
import { importBatchTask, queryTaskList } from './service';
import { SUCCESS_CODE } from '@/utils/request';
import { AddBatchTaskBean, BatchTaskItem } from './data';
import { useModel } from 'umi';

const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'BATCH.EXPORT.TEMPLATE': template,
    'BATCH.IMPORT.TASK': task,
    'BATCH.IMPORT.VIEW': view,
    'BATCH.IMPORT.REDO': redo,
  } = currUser;

  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: AddBatchTaskBean) {
    const hide = message.loading('正在添加');
    try {
      const res = await importBatchTask(fields);
      if (res.code === SUCCESS_CODE) {
        message.success('添加成功');
        handleAddModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(res.message || '添加失败');
      }
    } catch (error) {
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
    } finally {
      hide();
    }
  }

  const columns: ProColumns<BatchTaskItem>[] = [
    {
      title: '任务名称',
      dataIndex: 'name',
    },
    {
      title: '任务类型',
      dataIndex: 'task_type',
      valueEnum: {
        1: '路段导入',
        3: '设备导入',
      },
    },
    {
      title: '状态',
      dataIndex: 'task_status',
      valueEnum: {
        0: '待导入',
        1: '导入中',
        2: '全部成功',
        3: '部分成功',
        4: '导入失败',
      },
    },
    {
      title: '导入结果说明',
      dataIndex: 'result_message',
      search: false,
    },
    {
      hideInTable: !template,
      title: '结果下载',
      dataIndex: 'resultUrl',
      search: false,
      render: (_text, record) => {
        if (record.result_url) {
          return (
            <a href={record.result_url} target="_blank">
              下载
            </a>
          );
        }
        return '-';
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<BatchTaskItem>
        headerTitle="批量任务列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<BatchTaskItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => [
          <>
            {task && (
              <Button type="primary" onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 新增导入任务
              </Button>
            )}
          </>,
        ]}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        tableAlertRender={() => false}
        rowSelection={false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryTaskList({ page, pageSize, ...filter });
        }}
        columns={columns}
      />
      <AddFrom
        modalVisible={addModalVisible}
        onSubmit={(value: AddBatchTaskBean) => handleAdd(value)}
        onCancel={() => handleAddModalVisible(false)}
      />
    </PageHeaderWrapper>
  );
};

export default TableList;
